# -*- coding: utf-8 -*-
from config import OSS_HOST, OSS_APP_ID, OSS_APP_KEY
from lib.oss.oss_api import OssAPI


def oss_url(bucket, object_name):
    return 'http://' + bucket + '.' + OSS_HOST + '/' + object_name


def oss_url_download(bucket, object_name, time_out):
    ossAPI = OssAPI(OSS_HOST, OSS_APP_ID, OSS_APP_KEY)
    return ossAPI.sign_url('GET', bucket, object_name, time_out)


def oss_url_upload(bucket, object_name, time_out,
                   content_type='multipart/form-data'):
    ossAPI = OssAPI(OSS_HOST, OSS_APP_ID, OSS_APP_KEY)
    return ossAPI.sign_url('PUT', bucket, object_name, time_out,
                           {'Content-Type': content_type})


def oss_upload(file_path, bucket, object_name):

    # check file to upload
    import os
    if not os.path.exists(file_path) or not os.path.isfile(file_path):
        return False

    # upload to OSS
    ossAPI = OssAPI(OSS_HOST, OSS_APP_ID, OSS_APP_KEY)
    res = ossAPI.put_object_from_file(bucket, object_name, file_path)
    return (True if res.status == 200 else False)


def oss_check_exist(bucket, object_name):
    ossAPI = OssAPI(OSS_HOST, OSS_APP_ID, OSS_APP_KEY)
    res = ossAPI.head_object(bucket, object_name)
    if res.status == 200:
        return True
    return False


def oss_download(file_path, bucket, object_name):
    ossAPI = OssAPI(OSS_HOST, OSS_APP_ID, OSS_APP_KEY)
    res = ossAPI.get_object_to_file(bucket, object_name, file_path)
    return (True if res.status == 200 else False)
